package org.benjamin.tenancy.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.tenancy.domain.entity.Building;
import org.benjamin.tenancy.domain.entity.Housing;
import org.benjamin.tenancy.domain.entity.IncomeInfo;
import org.benjamin.tenancy.domain.entity.ReceiptBills;
import org.benjamin.tenancy.domain.entity.ReceiptParticulars;
import org.benjamin.tenancy.domain.entity.UtilitiesInfo;
import org.benjamin.tenancy.repository.BuildingRepository;
import org.benjamin.tenancy.repository.HousingRepository;
import org.benjamin.tenancy.repository.IncomeInfoRepository;
import org.benjamin.tenancy.repository.ReceiptInfoRepository;
import org.benjamin.tenancy.repository.ReceiptParticularsRepository;
import org.benjamin.tenancy.service.ReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ReceiptServiceImpl implements ReceiptService{
	
	private Logger logger = LogManager.getLogger();
	
	@Autowired
	private BuildingRepository buildingRepository;
	
	@Autowired
	private HousingRepository housingRepository;
	
	@Autowired
	private ReceiptInfoRepository receiptInfoRepository;
	
	@Autowired
	private ReceiptParticularsRepository receiptParticularsRepository;
	
	@Autowired
	private IncomeInfoRepository incomeInfoRepository;
	
	private void createReceipt() {
		
	}
	
	public void createReceiptByBuildingId(Integer yean,Integer month,Integer buildingId) {
		Building building = this.buildingRepository.findOne(buildingId);
		for(Housing housing : building.getHousings()) {
			this.createReceipt(yean, month, housing.getNumber());
		}
	}
	
	public void createReceiptByBuildingName(Integer yean,Integer month,String buildingName) {
		Building building = this.buildingRepository.findByName(buildingName);
		logger.info("门牌号{}，查询所有的房屋信息",buildingName);
		for(Housing housing : building.getHousings()) {
			this.createReceipt(yean, month, housing.getNumber());
		}
	}
	
	public void createReceipt(Integer yean,Integer month,String houseNumber) {
		Specification<Housing> specification = new Specification<Housing>() {
			
			@Override
			public Predicate toPredicate(Root<Housing> arg0, CriteriaQuery<?> arg1, CriteriaBuilder arg2) {
				// TODO Auto-generated method stub
				return null;
			}
		};
		Housing housing = this.housingRepository.findOne(specification);
		ReceiptBills receiptBills = new ReceiptBills();
		receiptBills.setClient(housing.getBuilding().getName()+" "+housing.getNumber());
		receiptBills.setName(housing.getTenant().getUsername());
		
		//租金
		ReceiptParticulars particulars = new ReceiptParticulars();
		particulars.setAmount(housing.getRental());
		particulars.setProduct("租金");
		particulars.setQuantity(BigInteger.ONE);
		particulars.setUnit("--");
		particulars.setUnitPrice(housing.getRental());
		receiptBills.getReceiptParticulars().add(particulars);
		
		//电费
		logger.info("计算电费");
		Integer beforeNumber = 0,cuentNumber = 0;
		for(UtilitiesInfo utilitiesInfo : housing.getUtilitiesInfos()) {
			if(utilitiesInfo.getType().equals(UtilitiesInfo.Type.ELECTRIC_NUMBER)) {
				if(utilitiesInfo.getMonth()== month) {
					cuentNumber = utilitiesInfo.getNumber();
				}else {
					logger.info("记录当前月份:{}",utilitiesInfo.getMonth());
					beforeNumber = utilitiesInfo.getNumber();
				}
			}
		}
		particulars = new ReceiptParticulars();
		particulars.setProduct("电费 ("+beforeNumber+" - "+cuentNumber+")");
		particulars.setQuantity(BigInteger.valueOf(cuentNumber-beforeNumber));
		particulars.setUnit("度");
		particulars.setUnitPrice(new BigDecimal(1.5));
		particulars.setAmount(new BigDecimal(particulars.getQuantity()).multiply(particulars.getUnitPrice()));
		receiptBills.getReceiptParticulars().add(particulars);
		
		//水费
		logger.info("计算水费");
		beforeNumber = 0;cuentNumber = 0;
		for(UtilitiesInfo utilitiesInfo : housing.getUtilitiesInfos()) {
			if(utilitiesInfo.getType().equals(UtilitiesInfo.Type.WATER_NUMBER)) {
				if(utilitiesInfo.getMonth() == month) {
					cuentNumber = utilitiesInfo.getNumber();
				}else {
					logger.info("获得上个月{}月份，水量是{}",utilitiesInfo.getMonth(),utilitiesInfo.getNumber());
					beforeNumber = utilitiesInfo.getNumber();
				}
			}
		}
		particulars = new ReceiptParticulars();
		particulars.setProduct("水费 ("+beforeNumber+" - "+cuentNumber+")");
		particulars.setQuantity(BigInteger.valueOf(cuentNumber - beforeNumber));
		particulars.setUnit("平方");
		particulars.setUnitPrice(new BigDecimal(10));
		particulars.setAmount(new BigDecimal(particulars.getQuantity()).multiply(particulars.getUnitPrice()));
		receiptBills.getReceiptParticulars().add(particulars);
		//计算总额
		BigDecimal sumAmount = BigDecimal.ZERO;
		for(ReceiptParticulars receiptParticulars : receiptBills.getReceiptParticulars()) {
			sumAmount.add(receiptParticulars.getAmount());
		}
		receiptBills.setSumMoney(sumAmount);
		
		//保存收据信息
		this.receiptParticularsRepository.save(receiptBills.getReceiptParticulars());
		this.receiptInfoRepository.save(receiptBills);
		IncomeInfo incomeInfo = new IncomeInfo();
		incomeInfo.setYeam(yean);
		incomeInfo.setMonth(month);
		incomeInfo.setAmount(receiptBills.getSumMoney());
		incomeInfo.setStatus(false);
		incomeInfo.setHousing(housing);
		this.incomeInfoRepository.save(incomeInfo);
	}

}
